package com.example.hospitalManage.controller.user.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.hospitalManage.config.annotation.TokenToNormalUser;
import com.example.hospitalManage.controller.user.param.UserUpdateParam;
import com.example.hospitalManage.entity.OrderOrderInfo;
import com.example.hospitalManage.entity.UserInfo;
import com.example.hospitalManage.service.PayOrderService;
import com.example.hospitalManage.utils.Response;
import com.example.hospitalManage.utils.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Description:
 * Param:
 * return:
 * Author: 彭雨胜
 * Data: 2022/12/31
 */
@RestController
@RequestMapping(value = "/api")
@Api(value = "v1",tags = "订单操作相关接口")
@CrossOrigin
public class PayOrderController {
    @Autowired
    private PayOrderService payOrderService;

    private static final Logger logger = LoggerFactory.getLogger(PayOrderController.class);

    @PostMapping("/order")
    @ApiOperation(value = "根据用户id，查找该用户的所有订单", notes = "")
    public ResponseResult queryOrderByUserId(@TokenToNormalUser UserInfo userInfo) {
        if (userInfo.equals(null)) {
            return Response.createFailResp("用户未登录！");
        } else {
            Long userId = userInfo.getId();
            // 构造查询条件
            QueryWrapper<OrderOrderInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId);
            List<OrderOrderInfo> orderList = payOrderService.list(wrapper);
            // 输出日志
            logger.info("user={} query his order.", userId);
            // 返回查询列表
            return Response.createOkResp(orderList);
        }
    }

    @Transactional
    @GetMapping ("/order/{id}")
    @ApiOperation(value = "支付订单", notes = "修改订单状态为支付（状态码为 1 ）")
    public ResponseResult updateOrderStatus(@TokenToNormalUser UserInfo userInfo, @PathVariable Long id) {

        // 判断用户是否携带token信息
        if (userInfo.equals(null)) {
            return Response.createFailResp("用户未登录！");
        } else {
            // 获取订单用户id
            OrderOrderInfo tempOrder = payOrderService.getById(id);
            Long tempUserId = tempOrder.getUserId();

            // token对应用户与订单用户相同
            if (tempUserId.equals(userInfo.getId())) {
                if (tempOrder.getOrderStatus().equals(1)) {
                    return Response.createFailResp("订单已支付！");
                } else if (tempOrder.getOrderStatus().equals(0)) {
                    OrderOrderInfo orderOrderInfo = new OrderOrderInfo();
                    orderOrderInfo.setId(id);
                    orderOrderInfo.setOrderStatus(1);
                    boolean flag = payOrderService.updateById(orderOrderInfo);
                    // 输出日志
                    logger.info("user={} pay for his order={}.", userInfo.getId(), orderOrderInfo.getId());
                    // 返回查询列表
                    if (flag) {
                        return Response.createOkResp("支付成功");
                    } else {
                        return Response.createFailResp("支付失败");
                    }
                } else {
                    return Response.createFailResp("订单已取消 或 订单已删除");
                }
            } else {
                return Response.createFailResp("非本人操作！");
            }

        }
    }

    @Transactional
    @PutMapping ("/order/{id}")
    @ApiOperation(value = "取消订单", notes = "设置状态码为-1")
    public ResponseResult cancelOrder(@TokenToNormalUser UserInfo userInfo, @PathVariable Long id) {
        if (userInfo.equals(null)) {
            return Response.createFailResp("用户未登录！");
        } else {
            // 获取订单用户id
            OrderOrderInfo tempOrder = payOrderService.getById(id);
            Long tempUserId = tempOrder.getUserId();

            // token对应用户与订单用户相同
            if (tempUserId.equals(userInfo.getId())) {
                if (tempOrder.getOrderStatus().equals(-1)) {
                    return Response.createFailResp("订单已取消！");
                } else {
                    OrderOrderInfo orderOrderInfo = new OrderOrderInfo();
                    orderOrderInfo.setOrderStatus(-1);
                    orderOrderInfo.setId(id);
                    // 返回取消信息
                    boolean flag = payOrderService.updateById(orderOrderInfo);
                    if (flag) {
                        return Response.createOkResp("订单取消成功！");
                    } else {
                        return Response.createFailResp("订单取消失败！");
                    }
                }
            } else {
                return Response.createFailResp("非本人操作！");
            }

        }
    }

    @Transactional
    @DeleteMapping ("/order/{id}")
    @ApiOperation(value = "删除订单", notes = "")
    public ResponseResult deleteOrder(@TokenToNormalUser UserInfo userInfo, @PathVariable Long id) {
        // 判断用户是否登录
        if (userInfo.equals(null)) {
            return Response.createFailResp("用户未登录！");
        } else {
            // 获取订单用户id
            OrderOrderInfo tempOrder = payOrderService.getById(id);
            Long tempUserId = tempOrder.getUserId();

            // token对应用户与订单用户相同
            if (tempUserId.equals(userInfo.getId())) {
                payOrderService.removeById(id);
                return Response.createOkResp("订单删除成功！");
            } else {
                return Response.createFailResp("非本人操作！");
            }

        }
    }
}
